<?php


namespace app\api\controller;

use app\api\model\MemberInfoModel;
use app\common\service\MemberService;
use library\logic\Page;
use think\facade\Request;

/**
 * @title   订单模块
 * @desc    预约订单和匹配订单API
 * Class Order
 * @package app\api\controller
 */
class Order extends AuthController {

    /**
     * 绑定数据表
     * @var string
     */
    protected $table = 'meetyou_order';

    /**
     * @title 积分预约
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function reservation() {
        //预约消耗积分
        $reservation_credit1 = intval(sysconf('meetyou_reservation_credit1'));
        if (empty($reservation_credit1)) $reservation_credit1 = 50;

        $member_info = $this->_userInfo;
        //检查积分
        $credit1 = $this->getCredit1();
        if ($credit1 < $reservation_credit1) $this->error('您的积分不够，请充值！');

        $member_level = $member_info['level'];
        //获取会员等级
        $level = $this->getMemberLevel($member_level);
        $time = time();

        //判断时间预约时间段
        $date_range = sysconf('meetyou_reservation_range');
        if (!empty($date_range)) {
            $date_range = explode(' - ', $date_range);
            $_start_time = strtotime(date('Y-m-d ') . $date_range[0]);
            $_end_time = strtotime(date('Y-m-d ') . $date_range[1]);
            if ($_start_time > $_end_time) {
                $_start_time = $_end_time + ($_end_time = $_start_time) * 0;
            }
            if ($time < $_start_time && $time > $_end_time) {
                $this->error('非预约时段，请等待！');
            }
        }

        //当前等级每天可预约次数
        $res_count = intval($level['rescount']);
        if ($res_count > 0) {
            $start_time = strtotime(date('Y-m-d', time()));
            $end_time = strtotime(date('Y-m-d', strtotime('+1 day')));
            //当天累计预约次数
            $res_total_count = intval(db($this->table)->where('mid', $member_info['id'])
                ->where('create_at', '>=', $start_time)
                ->where('create_at', '<', $end_time)
                ->count());

            if ($res_total_count >= $res_count) $this->error('您今天的可预约次数已用尽！');
        }

        //是否实名认证
        $info = MemberInfoModel::get($this->mid);
        if (empty($info)) {
            $this->error('请先完成实名认证！');
        } elseif ($info->verified != 1) {
            $this->error('请先完成实名认证！');
        }

        //创建预约订单
        if (MemberService::recharge($this->mid, $reservation_credit1 * -1, '预约扣除积分')) {
            db($this->table)->insert([
                'mid'       => $this->mid,
                'create_at' => $time,
                'update_at' => $time,
                'ordersn'   => createNO($this->table, 'ordersn', 'RES')
            ]);

            $this->success('已成功预约,正在排队');
        } else {
            $this->error('预约失败');
        }
    }

    /**
     * @title 预约订单列表
     * @param int page 1
     * @param int pzie 10
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function reservationList() {
        $psize = intval(input('psize', 10));
        $page = intval(input('page', 1));

        $offset = max(0, $page - 1) * $psize;
        $query = db($this->table)
            ->where('mid', $this->_userInfo['id'])
            ->where('status', 'in', ['0', '3'])
            ->where('finish_at', 0);
        $list = $query->limit($offset, $psize)
            ->order('create_at', 'desc')
            ->field('status,create_at')
            ->select();
        $count = $query->count();

        //预约匹配等待时间
        $wait_second = intval(sysconf('meetyou_reservation_wait_time') * 3600);
        $time = time();
        foreach ($list as &$row) {
            $row['wait'] = 0;
            if ($row['status'] == 0) {
                $row['wait'] = max(0, ($row['create_at'] + $wait_second) - $time);
            } else {

            }
        }
        unset($row);
        $this->success($count, $list);
    }


    /**
     * @title 获取预约会员信息列表
     * @param int page 1
     * @param int pzie 10
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function reservationMemberList() {
        $psize = intval(input('psize', 10));
        $page = intval(input('page', 1));

        $offset = max(0, $page - 1) * $psize;

        $query = db($this->table)
            ->where('mid', $this->_userInfo['id'])
            ->where('status', '1')
            ->where('pay_orderid', '<>', 0)
            ->where('pay_status', 0);
        $list = $query->limit($offset, $psize)
            ->order('create_at', 'desc')
            ->field('id as orderid,pay_orderid,reservation_at')
            ->select();
        $count = $query->count();

        foreach ($list as &$row) {
            $pay_info = db($this->table)->alias('o')
                ->leftJoin('meetyou_member m', 'm.id=o.mid')
                ->where('o.id', $row['pay_orderid'])
                ->field('o.mid,m.nickname,m.phone,m.avatar')
                ->find();
            if (empty($pay_info['avatar'])) $pay_info['avatar'] = '/static/img/avatar.png';
            $pay_info['avatar'] = Request::domain() . $pay_info['avatar'];
            $row['pay_info'] = $pay_info;
        }
        unset($row);
        $this->success($count, $list);
    }

    /**
     * 根据订单ID获取会员信息
     * @param $orderid
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getOrderMemberInfo($orderid) {
        $mid = db($this->table)->where('id', $orderid)->value('mid');
        if (!empty($mid)) {
            $member = db('meetyou_member')->where('id', $mid)->where('status', '<>', 0)->field('id,avatar,nickname,realname,phone,spare_phone,status')->find();
            if (!empty($member)) {
                $info = db('meetyou_member_info')->where('mid', $mid)->where('verified', 1)->find();
                if (!empty($info)) {
                    return [
                        'phone'         => $member['phone'],
                        'realname'      => $member['realname'],
                        'wechat'        => $info['wechat'],
                        'wechat_qrcode' => $info['wechat_qrcode'],
                        'alipay'        => $info['alipay'],
                        'alipay_qrcode' => $info['alipay_qrcode']
                    ];
                }
            }
        }
        return false;
    }


    /**
     * @title 获取预约订单会员信息
     * @param int orderid
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function getReservationMemberInfo() {
        $orderid = input('orderid');
        if (empty($orderid)) $this->error('无效的访问');
        $order = db($this->table)->where('id', $orderid)->field('pay_orderid,ordersn')->find();
        if (empty($order)) $this->error('无效的访问');
        $pay_orderid = $order['pay_orderid'];

        $member_info = $this->getOrderMemberInfo($pay_orderid);
        if ($member_info) {
            $member_info['ordersn'] = $order['ordersn'];
            $this->success('预约订单会员信息', $member_info);
        }
        //无效的匹配，还原订单
        db($this->table)->where('id', $orderid)->update([
            'status'      => 0,
            'pay_orderid' => 0
        ]);
        $this->error('无效的订单信息');

    }


    /**
     * @title 获取匹配订单列表
     * @param int page 1
     * @param int psize 10
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function transactionMemberList() {
        $psize = intval(input('psize', 10));
        $page = intval(input('page', 1));

        $offset = max(0, $page - 1) * $psize;

        $query = db($this->table)->alias('o')
            ->join($this->table . ' po ', 'po.pay_orderid = o.id')
            ->where('o.mid', $this->_userInfo['id'])
            ->where('o.status', '3');
        $list = $query->limit($offset, $psize)
            ->order('o.update_at', 'desc')
            ->field('po.id as orderid')
            ->select();
        $count = $query->count();

        foreach ($list as &$row) {
            $pay_info = db($this->table)->alias('o')
                ->leftJoin('meetyou_member m', 'm.id=o.mid')
                ->where('o.id', $row['orderid'])
                ->field('o.mid,m.nickname,m.phone,m.avatar')
                ->find();
            if (empty($pay_info['avatar'])) $pay_info['avatar'] = '/static/img/avatar.png';
            $pay_info['avatar'] = Request::domain() . $pay_info['avatar'];
            $row['pay_info'] = $pay_info;
        }
        unset($row);
        $this->success($count, $list);
    }

    /**
     * @title 获取匹配会员信息
     * @param int orderid - 订单ID
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getTransactionMemberInfo() {
        $orderid = input('orderid');
        if (empty($orderid)) $this->error('无效的访问');
        $order = db($this->table)->where('id', $orderid)->field('ordersn')->find();
        if (empty($order)) $this->error('无效的访问');

        $member_info = $this->getOrderMemberInfo($orderid);
        if ($member_info) {
            $member_info['ordersn'] = $order['ordersn'];
            $this->success('预约订单会员信息', $member_info);
        }
        $this->error('无效的订单信息');
    }

    /**
     * @title 获取当天可预约次数
     */
    public function getReCount() {
        $member_level = $this->_userInfo['level'];
        //获取会员等级
        $level = $this->getMemberLevel($member_level);
        //可预约数量
        $count = intval($level['rescount']);
        //已预约数量
        $start_time = strtotime(date('Y-m-d', time()));
        $end_time = strtotime(date('Y-m-d', strtotime('+1 day')));
        //当天累计预约次数
        $res_total_count = intval(db($this->table)->where('mid', $this->_userInfo['id'])
            ->where('create_at', '>=', $start_time)
            ->where('create_at', '<', $end_time)
            ->count());
        $this->success('可预约数量', [
            'res_count' => $count, //当天可预约次数
            'res_total' => $res_total_count // 当天已预约次数
        ]);
    }

}